import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams } from 'react-router-dom';
import axios from 'axios';
import FormData from 'form-data';
import UserListABI from '../contract/ABIs/UserList.json'; // 用户列表合约 ABI
import MarketplaceABI from '../contract/ABIs/Marketplace.json'; // 市场合约 ABI
import UserABI from '../contract/ABIs/User.json'; // 用户合约 ABI
import MaterialListAddr from '../contract/ADDRESSes/MaterialListAddr'; // 市场合约地址
import UserListAddr from '../contract/ADDRESSes/UserListAddr'; // 用户列表合约地址
import './addProduct.css'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlusCircle } from '@fortawesome/free-solid-svg-icons';

const JWT = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mb3JtYXRpb24iOnsiaWQiOiJiODVmNDg2OC0yNWZlLTRkZWItOGUxOS1iYTZhYjg4ZmUyOGIiLCJlbWFpbCI6Im1laXp6aWxhaWNoaW5nNDUxQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJwaW5fcG9saWN5Ijp7InJlZ2lvbnMiOlt7ImlkIjoiRlJBMSIsImRlc2lyZWRSZXBsaWNhdGlvbkNvdW50IjoxfSx7ImlkIjoiTllDMSIsImRlc2lyZWRSZXBsaWNhdGlvbkNvdW50IjoxfV0sInZlcnNpb24iOjF9LCJtZmFfZW5hYmxlZCI6ZmFsc2UsInN0YXR1cyI6IkFDVElWRSJ9LCJhdXRoZW50aWNhdGlvblR5cGUiOiJzY29wZWRLZXkiLCJzY29wZWRLZXlLZXkiOiIzYjdlMmZlYTQwOTA2NjY4NTAyZCIsInNjb3BlZEtleVNlY3JldCI6IjAzNWUyZTRiZTM2NDg0NTFmYzFkOTRkMzhjNmRkMTJhMWVmMjEyYTM4YzJhYmE4OWNmMjNiNjk4NTkwMTg1NzkiLCJpYXQiOjE3MTgzMzE5Mzh9.dSVuazN5PYS9152mG4op-ugWX9rsAWRMbdYv5PmZeg8';

const pinFileToIPFS = async (file) => {
    const formData = new FormData();
    formData.append('file', file);


    const pinataMetadata = JSON.stringify({
        name: 'File name',
    });
    formData.append('pinataMetadata', pinataMetadata);

    const pinataOptions = JSON.stringify({
        cidVersion: 0,
    })
    formData.append('pinataOptions', pinataOptions);

    try {
        const res = await axios.post("https://api.pinata.cloud/pinning/pinFileToIPFS", formData, {
            maxBodyLength: "Infinity",
            headers: {
                'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
                'Authorization': `Bearer ${JWT}`
            }
        });
        return res.data.IpfsHash;
    } catch (error) {
        console.log(error);
        throw new Error('Failed to upload file to IPFS');
    }
};

const AddProduct = () => {
    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { userAddr } = useParams();
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [price, setPrice] = useState('');
    const [quantity, setQuantity] = useState('');
    const [category, setCategory] = useState('');
    const [image, setImage] = useState(null);
    const [ContractUserList, setContractUserList] = useState(null);
    const [ContractMaterial, setContractMaterial] = useState(null);
    const [ContractUser, setContractUser] = useState(null);
    const [imagePreview, setImagePreview] = useState(null);
    // 定义下拉选项
    const categories = [
        '宠物',
        '电子产品',
        '技术服务',
        '服饰',
        '鞋包',
        '生鲜',
        '其他',
        // ...更多选项
    ];

    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建用户列表合约实例
                    const UserListInstance = new web3Instance.eth.Contract(
                        UserListABI,
                        UserListAddr
                    );
                    setContractUserList(UserListInstance);

                    // 创建市场合约实例
                    const MaterialListInstance = new web3Instance.eth.Contract(
                        MarketplaceABI,
                        MaterialListAddr
                    );
                    setContractMaterial(MaterialListInstance);

                    // 创建用户合约实例
                    const UserInstance = new web3Instance.eth.Contract(
                        UserABI,
                        userAddr
                    );
                    setContractUser(UserInstance);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, []);

    const handleImageUpload = async () => {
        try {
            const ipfsHash = await pinFileToIPFS(image);
            return ipfsHash;
        } catch (error) {
            console.error('图片上传失败', error);
        }
    };

    const addProduct = async () => {
        try {
            const accounts = await web3.eth.getAccounts();
            const ipfsHash = await handleImageUpload();
            console.log('ipfsHash:', ipfsHash);
            console.log('userAddr, name, description, price, quantity, ipfsHash, category:', userAddr, name, description, price, quantity, ipfsHash, category);
            await ContractMaterial.methods.addProduct(userAddr, name, description, price, quantity, ipfsHash, category).send({ from: accounts[0] });
            alert('商品添加成功');
        } catch (error) {
            console.error('商品添加失败', error);
        }
    };

    const handleImageChange = (e) => {
        const file = e.target.files[0];
        setImage(file);

        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                setImagePreview(e.target.result);
            };
            reader.readAsDataURL(file);
        }
    };

    return (
        <div className="addProductContainer">
            <div className="addProductHeader">
                <h2>发布商品</h2>
            </div>
            <div className="addProductForm">
                <div className="form-group">
                    <label htmlFor="name">商品名称:</label>
                    <input type="text" id="name" placeholder="商品名称" value={name} onChange={(e) => setName(e.target.value)} />
                </div>
                <div className="form-group">
                    <label htmlFor="description">商品描述:</label>
                    <textarea id="description" placeholder="商品描述" value={description} onChange={(e) => setDescription(e.target.value)} />
                </div>
                <div className="form-group">
                    <label htmlFor="price">价格:</label>
                    <input type="text" id="price" placeholder="价格" value={price} onChange={(e) => setPrice(e.target.value)} />
                </div>
                <div className="form-group">
                    <label htmlFor="quantity">数量:</label>
                    <input type="number" id="quantity" placeholder="数量" value={quantity} onChange={(e) => setQuantity(e.target.value)} />
                </div>
                <div className="form-group">
                    <label htmlFor="category">分类:</label>
                    {/* 使用 select 元素创建下拉框 */}
                    <select
                        id="category"
                        value={category}
                        onChange={(e) => setCategory(e.target.value)}
                    >
                        <option value="">请选择分类</option>
                        {/* 遍历 categories 数组，动态生成 option 元素 */}
                        {categories.map((categoryOption) => (
                            <option key={categoryOption} value={categoryOption}>
                                {categoryOption}
                            </option>
                        ))}
                    </select>                </div>
                <div className="form-group">
                    <label htmlFor="image">商品图片:</label>
                    <div className="upload-container">
                        <FontAwesomeIcon icon={faPlusCircle} className="upload-icon" />
                        <input type="file" id="image" accept="image/*" onChange={handleImageChange} />
                        {imagePreview && (
                            <img src={imagePreview} alt="商品预览" className="image-preview" />
                        )}
                        {!imagePreview && (
                            <div className="upload-placeholder">
                                点击上传图片
                            </div>
                        )}
                    </div>
                </div>
                <button onClick={addProduct} className="addProductButton">发布</button>
            </div>
        </div>
    );
};

export default AddProduct;